package com.dm.cloud.images.util;

import cn.hutool.core.io.FileUtil;
import com.dm.cloud.core.exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

@Component
public class NfsFileUtil {

    private static File nfsDir;

    @Value("${dm.images.nfs.path}")
    private String hfsPath;

    private static List<String> editTypes;

    private static Long exitMaxLeng;

    /**
     * 是否支持编辑
     * @param fileSuffix 文件后缀，不带点
     * @return
     */
    public static boolean hasEditTypes(String fileSuffix) {
        return editTypes.contains(fileSuffix.toLowerCase(Locale.ROOT));
    }

    /**
     * 断言文件长度是否能编辑
     * @param length
     */
    public static void hasLengthEdit(long length) {
        if(exitMaxLeng-length<0){
            throw new CustomException("文件内容过大,不支持在线编辑,最大不超过"+exitMaxLeng/1024+"KB!");
        }
    }

    @Autowired
    public void setEditTypes(@Value("${dm.images.nfs.edit-type}") String editType){
        NfsFileUtil.editTypes= Arrays.asList(editType.toLowerCase(Locale.ROOT).split(","));
    }

    @Autowired
    public void setExitMaxLeng(@Value("${dm.images.nfs.edit-max-leng}") Long exitMaxLeng){
        NfsFileUtil.exitMaxLeng=exitMaxLeng;
    }

    /**
     * 获取文件于相对路径
     * @param file
     * @return
     */
    public static String relativePath(File file){
        return file.getAbsolutePath().replace(nfsDir.getAbsolutePath(),"");
    }

    /**
     * 创建子目录
     * @param rootPath
     * @return
     */
    public static File mkChildDir(String rootPath) {
        File dirPath = new File(nfsDir.getAbsolutePath() + File.separator + rootPath);
        File dir=FileUtil.mkdir(dirPath);
        return dir;
//        if(!dirPath.exists() || !dirPath.isDirectory()){
//            dirPath.mkdirs();
//        }
//        return dirPath;
    }

    /**
     * 获取子目录
     * @param rootPath
     * @return
     */
    public static File getChildDir(String rootPath) {
        String dirPath = nfsDir.getAbsolutePath() + File.separator + rootPath;
        File f = new File(dirPath);
        if(!f.exists()){
            throw new CustomException("共享目录:"+rootPath+"  不存在！");
        }
        return f;
    }

    @PostConstruct
    public void init(){
        nfsDir=new File(hfsPath);
        if(!nfsDir.exists() || !nfsDir.isDirectory()){
            throw new CustomException("nfs目录不能为空！");
        }
    }



}
